//
//  JgAdsRewardedVideoAdapter.m
//  AnyThinkSDKDemo
//
//  Created by 刘娟 on 2022/10/17.
//  Copyright © 2022 抽筋的灯. All rights reserved.
//

#import "JgAdsRewardedVideoAdapter.h"
#import "JgAdsRewardedVideoCustomEvent.h"
#import <AnyThinkRewardedVideo/AnyThinkRewardedVideo.h>
#import "JgAdsRewardVodAdContainer.h"

#import "ATJgAdsBiddingRequest.h"
#import "ATJgAdsBiddingManager.h"
@interface JgAdsRewardedVideoAdapter()
@property(nonatomic, readonly) JgAdsRewardedVideoCustomEvent *customEvent;
@property(nonatomic, strong)JgAdsRewardVodAdContainer *rewardVodAdContainer;
@end

@implementation JgAdsRewardedVideoAdapter

+(BOOL) adReadyWithCustomObject:(id)customObject info:(NSDictionary*)info {
    //极光ads没有是否有效字段 默认有效
    return YES;
}

+(void) showRewardedVideo:(ATRewardedVideo*)rewardedVideo inViewController:(UIViewController*)viewController delegate:(id<ATRewardedVideoDelegate>)delegate {
    JgAdsRewardedVideoCustomEvent *customEvent = (JgAdsRewardedVideoCustomEvent*)rewardedVideo.customEvent;
    customEvent.delegate = delegate;
    [customEvent.expressRvAdContainer showRewardVodAdWithRootViewController:viewController];
}

-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    self = [super init];
    if (self != nil) {
#if DEBUG
        NSLog(@"=======JgAdsSDK appid:%@",serverInfo[@"app_id"]);
#endif
        [JgAdsSDK initWithAppId:serverInfo[@"app_id"] completionBlock:^(NSError * _Nullable error) {
            if (error) {
                NSLog(@"JgAdsSDK init failed:%@",error);
            }
        }];
    }
    return self;
}

-(void) loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion {
    dispatch_async(dispatch_get_main_queue(), ^{
#if DEBUG
        NSLog(@"=======JgAdsSDK serverInfo:%@\nlocalInfo%@",serverInfo,localInfo);
#endif
        self->_customEvent = [[JgAdsRewardedVideoCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
        self->_customEvent.requestCompletionBlock = completion;
        
        NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
        if (bidId.length) {
            
            ATJgAdsBiddingRequest *request = [[ATJgAdsBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"slot_id"]];
            
            if (request.customObject!=nil) { // load secced
                self.rewardVodAdContainer = request.customObject;
                self.rewardVodAdContainer.delegate = self->_customEvent;
                self->_customEvent.expressRvAdContainer = self.rewardVodAdContainer;
                [self->_customEvent trackRewardedVideoAdLoaded:self.rewardVodAdContainer adExtra:nil];
            } else { // fail
                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:-1000001 userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load intertitial.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [self->_customEvent trackRewardedVideoAdLoadFailed:error];
            }
            [[ATJgAdsBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"slot_id"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_customEvent loadRawardVodWithPosId:serverInfo[@"slot_id"]];

            });
        }
    });
}
#pragma mark - Header bidding
#pragma mark - c2s
+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {

    NSLog(@"%s", __FUNCTION__);
    if (NSClassFromString(@"JgAdsSDK") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"JgAdsSDK is not imported"}]); }
        return;
    }
    [JgAdsSDK initWithAppId:info[@"app_id"] completionBlock:^(NSError * _Nullable error) {
        if (error){
            NSLog(@"JgAdsSDK 初始化失败%@",error);
        } else {
            
            ATJgAdsBiddingManager *biddingManage = [ATJgAdsBiddingManager sharedInstance];
            ATJgAdsBiddingRequest *request = [ATJgAdsBiddingRequest new];
            request.unitGroup = unitGroupModel;
            request.placementID = placementModel.placementID;
            request.bidCompletion = completion;
            request.unitID = info[@"slot_id"];
            request.extraInfo = info;
            request.adType = ESCAdFormatReward;
            JgAdsRewardVodAdContainer *rewardVodAdContainer = [[JgAdsRewardVodAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil];
            request.customObject = rewardVodAdContainer;
            [biddingManage startWithRequestItem:request];
            [rewardVodAdContainer loadRewardVodAd];
            
        }
    }];
}


+ (void) sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    JgAdsRewardVodAdContainer *rewardVodAdContainer = (JgAdsRewardVodAdContainer *)customObject;
    [rewardVodAdContainer sendWinNotificationWithPrice:[rewardVodAdContainer getBidPrice]];
#if DEBUG
    NSLog(@"jgads=============激励视频-上报竞赢价格：%ld",[rewardVodAdContainer getBidPrice]);
#endif
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    //美元转人民币，转换为分
    CGFloat cnyPrice = price.floatValue * 6.3 * 100;
    JgAdsRewardVodAdContainer *rewardVodAdContainer = (JgAdsRewardVodAdContainer *)customObject;
    JgAdsBiddingLossReason reason = JgAdsBiddingLossReasonOther;
    if (lossType == ATBiddingLossWithLowPriceInNormal || lossType == ATBiddingLossWithLowPriceInHB) {
        reason = JgAdsBiddingLossReasonLowPrice;
    }
    [rewardVodAdContainer sendWinFailNotificationReason:reason winnerPirce:@(cnyPrice).integerValue];
#if DEBUG
    NSLog(@"jgads=============激励视频-上报竞败；竞败原因：%ld竞赢价格：%ld",(long)reason,@(cnyPrice).integerValue);
#endif
}

@end
